const socket = require("socket.io");
const path = require("path");
const createUserName = require(path.join(__dirname, "./utils/createUserName"));
const createRoom = require(path.join(__dirname, "./utils/createRoom"));
exports.getSocket = (server) => {
  const io = socket(server, {
    cors: {
      origin: "*",
    },
  });
  const channel = new Map();
  // channel.set("PUBG灵魂上分车队", {
  //   room: "1234",
  //   player: [
  //     {
  //       io: "22132",
  //       name: "袁小哔",
  //     },
  //   ],
  // });

  io.on("connection", (socket) => {
    // createUserName.createUserName()
    let username = socket.handshake.query.username;
    if (username === "null") {
      socket.username = createUserName.createUserName();
    } else {
      socket.username = username;
    }

    socket.on("channelList", (fn) => {
      // 将 Map 对象转换为对象
      const mapToObject = Object.fromEntries(channel);
      fn(mapToObject);
    });
    socket.on("playerList", (obj, fn) => {
      const { name, password, recall } = obj;
      if (!channel.has(name))
        return fn({ status: 1, message: "没有找到这个频道, 请删除后重试" });
      if (channel.get(name).password !== null && !password) {
        fn({
          status: 2,
          message: "请输入密码",
        });
        return;
      }
      if (channel.get(name).password !== null && password) {
        if (channel.get(name).password !== password) {
          fn({
            status: 3,
            message: "密码错误",
          });
          return;
        }
      }
      socket.peerId = obj.peerId;
      socket.joinRoom = channel.get(name).room;
      socket.join(channel.get(name).room);
      let player = [];
      if (io.sockets.adapter.rooms.has(channel.get(name).room)) {
        let playerList = io.sockets.adapter.rooms.get(channel.get(name).room);
        // console.log(playerList);
        playerList.forEach((element) => {
          player.push({
            name: io.sockets.sockets.get(element).username,
            id: io.sockets.sockets.get(element).id,
            peerId: io.sockets.sockets.get(element).peerId,
            isVideo: io.sockets.sockets.get(element).isVideo,
          });
        });
      }
      if (!recall) {
        socket.to(channel.get(name).room).emit("userJoined", {
          name: socket.username,
          id: socket.id,
          peerId: socket.peerId,
        });
      }
      fn({
        status: 0,
        message: player,
      });
    });
    socket.on("addChannel", (obj, fn) => {
      if (channel.has(obj.name)) {
        fn({
          status: 1,
          message: "频道名已经存在了。",
        });
        return;
      }
      channel.set(obj.name, {
        password: obj.password ? obj.password : null,
        room: createRoom.createRoom(),
      });
      socket.emit("newChannel", {
        name: obj.name,
      });
      fn({
        status: 0,
        message: "添加成功",
      });
    });

    socket.on("send-message", (message, fn) => {
      let room = socket.joinRoom;
      if (!io.sockets.adapter.rooms.has(room)) {
        fn({
          status: 1,
          message: "进入频道失败,请重试",
        });
        return;
      }
      fn({
        status: 0,
        message: "success",
      });
      io.to(room).emit("receive-message", {
        name: socket.username,
        message: message,
        id: socket.id,
      });
    });
    // socket.on('re-call', () => {
    //   room = socket.joinRoom
    //   socket.to(socket.joinRoom).emit('call-one', socket.peerId)
    // })
    socket.on("getName", (id, fn) => {
      if (!io.sockets.sockets.has(id)) return;
      console.log(io.sockets.sockets.get(id).username);
      fn(io.sockets.sockets.get(id).username);
    });
    socket.on("test", () => {
      console.log("进入测试模式");
    });
    socket.on("anwser", (id, isCanavs, fn) => {
      io.sockets.sockets.get(id).emit("recive", isCanavs, () => {
        fn();
      });
    });
    socket.on("re-offer", (offer) => {
      socket.to(socket.joinRoom).emit("re-offer", offer);
    });
    socket.on("re-anwser", (anwser) => {
      socket.to(socket.joinRoom).emit("re-anwser", anwser);
    });
    socket.on("ice-candidate", (ice) => {
      socket.to(socket.joinRoom).emit("ice-candidate", ice);
    });
    socket.on("video-show", (isVideo) => {
      socket.isVideo = isVideo;
      socket.to(socket.joinRoom).emit("video-show", {
        id: socket.id,
        isVideo,
      });
    });
    socket.on("change-name", (mes) => {
      socket.username = mes;
      if (socket.joinRoom)
        socket.to(socket.joinRoom).emit("change-name", {
          id: socket.id,
          username: mes,
        });
    });
    socket.on("leaveRoom", leaveRoom);
    // socket.on("disconnecting", () => {
    //   leaveRoom()
    // });
    socket.on('disconnect', leaveRoom)
    function leaveRoom() {
      if (!socket.joinRoom || !io.sockets.adapter.rooms.has(socket.joinRoom))
        return;
      socket.leave(socket.joinRoom);
      // 向其他用户发送通知，告知有用户离开了房间
      socket.to(socket.joinRoom).emit("userLeft", socket.id);
      socket.joinRoom = null;
      socket.isVideo = false;
    }
  });
};


